package top.codedance.iotp.iot.sdk;

import top.codedance.iotp.loadblance.IotServerLoadBlance;
import top.codedance.iotp.loadblance.common.AlgorithmType;
import top.codedance.iotp.loadblance.entiy.RegistyUri;

import java.util.List;

public abstract class AbstractWsDistributedService implements IotWsService {

    protected List<RegistyUri> registyHosts;
    protected String deviceId = null;
    protected IotServerLoadBlance iotServerLoadBlance;
    protected String wsServerHost;
    protected String route;

    public AbstractWsDistributedService(List<RegistyUri> registyHosts, String route, String deviceId) {
        this.registyHosts = registyHosts;
        this.route = route;
        this.deviceId = deviceId;
        this.iotServerLoadBlance = IotServerLoadBlance.getInstance(this.registyHosts);
        this.wsServerHost = this.iotServerLoadBlance.blanceWs(this.deviceId);
    }

    public AbstractWsDistributedService(List<RegistyUri> registyHosts, String route, AlgorithmType at, String deviceId) {
        this.registyHosts = registyHosts;
        this.route = route;
        this.deviceId = deviceId;
        this.iotServerLoadBlance = IotServerLoadBlance.getInstance(this.registyHosts, at);
        this.wsServerHost = this.iotServerLoadBlance.blanceWs(this.deviceId);
    }

    protected WsClient request(WsCallbacker callbacker){
        if(this.wsServerHost != null) {
            WsClient wsClient = new WsClient(this.wsServerHost + "/services/" + route, callbacker);
            if(wsClient.isOver()){
                this.wsServerHost = this.iotServerLoadBlance.reBlanceWs(this.deviceId);
            }
            return wsClient;
        }else{
            this.wsServerHost = this.iotServerLoadBlance.reBlanceWs(this.deviceId);
            System.out.println("WsLoadBlance: load blance fail.");
            return null;
        }
    }
}
